package com.yc.iot.rest;

import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;



import com.yc.iot.db.User;
import com.yc.iot.db.UserRepository;

@RestController
@RequestMapping(value="/")
public class ycRestController {
	
    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();
    @Autowired // This means to get the bean called userRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;
    
    private static final Logger log = LoggerFactory.getLogger(ycRestController.class);  
    
    @GetMapping(path="/greeting")	
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
    
    @GetMapping(path="/addUser")	
    public @ResponseBody String addUser(@RequestParam String name
			, @RequestParam String email) {
		// @ResponseBody means the returned String is the response, not a view name
		// @RequestParam means it is a parameter from the GET or POST request
        log.info("recv rest request");
		User n = new User();
		n.setName(name);
		n.setEmail(email);
		userRepository.save(n);
		return "Saved";
	}
    
    @GetMapping(path="/getUser")
	public @ResponseBody Iterable<User> getUser() {
		// This returns a JSON or XML with the users
		return userRepository.findAll();
	}
}